/*
* @Date: 2021/2/13
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import WebSocket from 'ws';
import config from './config';
import rabbitmq from './core/rabbitmq';

let wss = new WebSocket.Server({ port: config.socket.port });
let titleClients = {};
wss.on('connection', function(ws) {
  ws.on('message', function(data) {
    const commands = data.split(':');
    if (commands.length > 0) {
      const command = commands[0];
      const titles = commands[1].split(',');
      for (let i = 0; i < titles.length; i++) {
        const title = titles[i];
        if (!titleClients[title]) {
          titleClients[title] = [];
        }
        if (command === 'A') {
          if (titleClients[title].findIndex(vo => vo === ws) === -1) {
            titleClients[title].push(ws);
          }
        } else if (command === 'D'){
          const index = titleClients[title].findIndex(ws);
          if (index >= 0) {
            titleClients[title].splice(index, 1);
          }
        }
      }
    }
  });
  ws.on('close', function() {
    console.log('ws close');
    for (let key in titleClients) {
      const tIndex = titleClients[key].findIndex(vo => vo === ws);
      if (tIndex >= 0) {
        titleClients[key].splice(tIndex, 1);
      }
    }
  });
  ws.on('error', function() {
    console.log('ws error');
    for (let key in titleClients) {
      const tIndex = titleClients[key].findIndex(vo => vo === ws);
      if (tIndex >= 0) {
        titleClients[key].splice(tIndex, 1);
      }
    }
  });
});

rabbitmq.getChannel().then(ch => {
  ch.assertExchange('quotation', 'direct', { durable: false });
  ch.assertQueue('', { exclusive: true }).then(q => {
    ch.bindQueue(q.queue, 'quotation', 'info');
    ch.consume(q.queue, msg => {
      const content = msg.content.toString();
      const cmds = content.split(':');
      if (cmds.length > 0) {
        const title = cmds[0];
        if (titleClients[title]) {
          for (let i = 0; i < titleClients[title].length; i++) {
            const ws = titleClients[title][i];
            ws.send(content);
          }
        }
      }
      ch.ack(msg);
    }, { noAck: false });
  }).catch(err => {
    console.log('socket error', err);
  });
}).catch(err => {
  console.log('getChannel===>', err);
});

